<template>
  <div class="role-list-container">
    <!-- 搜索筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="角色名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入角色名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="角色编码">
          <el-input
            v-model="searchForm.code"
            placeholder="请输入角色编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="全部" value="" />
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>

        <el-form-item label="创建时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <IconifyIconOffline icon="ep:search" class="mr-1" />
            搜索
          </el-button>
          <el-button @click="handleReset">
            <IconifyIconOffline icon="ep:refresh" class="mr-1" />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-bar">
        <div class="action-left">
          <el-button type="primary" @click="handleCreate">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            新增角色
          </el-button>
          <el-button
            type="danger"
            :disabled="selectedRoles.length === 0"
            @click="handleBatchDelete"
          >
            <IconifyIconOffline icon="ep:delete" class="mr-1" />
            批量删除
          </el-button>
          <el-button type="success" @click="handleExport">
            <IconifyIconOffline icon="ep:download" class="mr-1" />
            导出数据
          </el-button>
        </div>

        <div class="action-right">
          <el-button circle @click="handleRefresh">
            <IconifyIconOffline icon="ep:refresh" />
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 角色列表 -->
    <el-card class="table-card" shadow="never">
      <el-table
        v-loading="loading"
        :data="roleList"
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />

        <el-table-column prop="id" label="ID" width="80" />

        <el-table-column prop="name" label="角色名称" min-width="150">
          <template #default="{ row }">
            <div class="role-name">
              <IconifyIconOffline
                :icon="getRoleIcon(row.code)"
                class="role-icon"
              />
              <span>{{ row.name }}</span>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="code" label="角色编码" width="150" />

        <el-table-column
          prop="description"
          label="角色描述"
          min-width="200"
          show-overflow-tooltip
        />

        <el-table-column
          prop="userCount"
          label="用户数量"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-link type="primary" @click="viewRoleUsers(row)">
              {{ row.userCount }}
            </el-link>
          </template>
        </el-table-column>

        <el-table-column
          prop="permissionCount"
          label="权限数量"
          width="100"
          align="center"
        >
          <template #default="{ row }">
            <el-tag type="info" size="small">
              {{ row.permissionCount }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>

        <el-table-column prop="sort" label="排序" width="100" align="center" />

        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>

        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              type="primary"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handlePermission(row)"
            >
              权限
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              :disabled="row.isSystem"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色详情弹窗 -->
    <el-dialog v-model="detailVisible" title="角色详情" width="600px">
      <div v-if="currentRole" class="role-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="角色ID">{{
            currentRole.id
          }}</el-descriptions-item>
          <el-descriptions-item label="角色名称">{{
            currentRole.name
          }}</el-descriptions-item>
          <el-descriptions-item label="角色编码">{{
            currentRole.code
          }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag
              :type="currentRole.status === 'enabled' ? 'success' : 'danger'"
            >
              {{ currentRole.status === "enabled" ? "启用" : "禁用" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="用户数量">{{
            currentRole.userCount
          }}</el-descriptions-item>
          <el-descriptions-item label="权限数量">{{
            currentRole.permissionCount
          }}</el-descriptions-item>
          <el-descriptions-item label="排序">{{
            currentRole.sort
          }}</el-descriptions-item>
          <el-descriptions-item label="系统角色">
            <el-tag :type="currentRole.isSystem ? 'warning' : 'info'">
              {{ currentRole.isSystem ? "是" : "否" }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="角色描述" :span="2">
            {{ currentRole.description || "-" }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{
            formatDateTime(currentRole.createTime)
          }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{
            formatDateTime(currentRole.updateTime)
          }}</el-descriptions-item>
        </el-descriptions>

        <div
          v-if="currentRole.permissions && currentRole.permissions.length > 0"
          class="role-permissions"
        >
          <h4>角色权限</h4>
          <div class="permission-tree">
            <div
              v-for="permission in currentRole.permissions"
              :key="permission.id"
              class="permission-item"
            >
              <el-tag size="small" class="permission-tag">
                {{ permission.name }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 权限配置弹窗 -->
    <el-dialog v-model="permissionVisible" title="权限配置" width="800px">
      <div v-if="currentRole" class="permission-config">
        <div class="config-header">
          <span>为角色 "{{ currentRole.name }}" 配置权限</span>
        </div>

        <el-tree
          ref="permissionTreeRef"
          :data="permissionTree"
          :props="treeProps"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          class="permission-tree"
        >
          <template #default="{ node, data }">
            <div class="tree-node">
              <IconifyIconOffline
                :icon="data.icon || 'ep:folder'"
                class="node-icon"
              />
              <span class="node-label">{{ node.label }}</span>
              <el-tag v-if="data.type" size="small" class="node-type">
                {{ getPermissionTypeText(data.type) }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </div>

      <template #footer>
        <el-button @click="permissionVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSavePermissions"
          >保存</el-button
        >
      </template>
    </el-dialog>

    <!-- 角色用户弹窗 -->
    <el-dialog v-model="usersVisible" title="角色用户" width="800px">
      <div v-if="currentRole" class="role-users">
        <div class="users-header">
          <span>角色 "{{ currentRole.name }}" 的用户列表</span>
          <el-button type="primary" size="small" @click="handleAssignUsers">
            <IconifyIconOffline icon="ep:plus" class="mr-1" />
            分配用户
          </el-button>
        </div>

        <el-table :data="roleUsers" stripe>
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="username" label="用户名" width="120" />
          <el-table-column prop="realName" label="真实姓名" width="120" />
          <el-table-column prop="phone" label="手机号" width="130" />
          <el-table-column prop="email" label="邮箱" min-width="180" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                {{ row.status === "active" ? "正常" : "禁用" }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button
                type="danger"
                link
                size="small"
                @click="handleRemoveUser(row)"
              >
                移除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox, type ElTree } from "element-plus";
import { IconifyIconOffline } from "@/components/ReIcon";
import dayjs from "dayjs";

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  name: "",
  code: "",
  status: "",
  dateRange: []
});

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
});

// 状态
const loading = ref(false);
const selectedRoles = ref([]);
const detailVisible = ref(false);
const permissionVisible = ref(false);
const usersVisible = ref(false);
const currentRole = ref(null);
const permissionTreeRef = ref<InstanceType<typeof ElTree>>();

// 权限树配置
const treeProps = {
  children: "children",
  label: "name"
};

const checkedPermissions = ref([]);

// 角色列表数据
const roleList = ref([
  {
    id: 1,
    name: "超级管理员",
    code: "super_admin",
    description: "系统超级管理员，拥有所有权限",
    userCount: 1,
    permissionCount: 50,
    status: "enabled",
    sort: 1,
    isSystem: true,
    createTime: "2023-01-01 00:00:00",
    updateTime: "2024-01-20 10:30:00",
    permissions: [
      { id: 1, name: "系统管理" },
      { id: 2, name: "用户管理" },
      { id: 3, name: "角色管理" }
    ]
  },
  {
    id: 2,
    name: "管理员",
    code: "admin",
    description: "系统管理员，拥有大部分管理权限",
    userCount: 3,
    permissionCount: 35,
    status: "enabled",
    sort: 2,
    isSystem: false,
    createTime: "2023-01-15 10:00:00",
    updateTime: "2024-01-18 14:20:00",
    permissions: [
      { id: 2, name: "用户管理" },
      { id: 4, name: "活动管理" },
      { id: 5, name: "赛事管理" }
    ]
  },
  {
    id: 3,
    name: "运营专员",
    code: "operator",
    description: "运营专员，负责内容管理和运营工作",
    userCount: 5,
    permissionCount: 20,
    status: "enabled",
    sort: 3,
    isSystem: false,
    createTime: "2023-02-01 09:30:00",
    updateTime: "2024-01-15 16:45:00",
    permissions: [
      { id: 4, name: "活动管理" },
      { id: 6, name: "资讯管理" },
      { id: 7, name: "广告管理" }
    ]
  },
  {
    id: 4,
    name: "普通用户",
    code: "user",
    description: "普通用户，基础功能权限",
    userCount: 156,
    permissionCount: 8,
    status: "enabled",
    sort: 4,
    isSystem: true,
    createTime: "2023-01-01 00:00:00",
    updateTime: "2024-01-10 11:20:00",
    permissions: [
      { id: 8, name: "个人信息" },
      { id: 9, name: "参与活动" }
    ]
  }
]);

// 权限树数据
const permissionTree = ref([
  {
    id: 1,
    name: "系统管理",
    icon: "ep:setting",
    type: "menu",
    children: [
      { id: 11, name: "用户管理", icon: "ep:user", type: "menu" },
      { id: 12, name: "角色管理", icon: "ep:avatar", type: "menu" },
      { id: 13, name: "权限管理", icon: "ep:key", type: "menu" },
      { id: 14, name: "系统设置", icon: "ep:tools", type: "menu" }
    ]
  },
  {
    id: 2,
    name: "内容管理",
    icon: "ep:document",
    type: "menu",
    children: [
      { id: 21, name: "活动管理", icon: "ep:calendar", type: "menu" },
      { id: 22, name: "赛事管理", icon: "ep:trophy", type: "menu" },
      { id: 23, name: "比赛管理", icon: "ep:medal", type: "menu" },
      { id: 24, name: "资讯管理", icon: "ep:news", type: "menu" },
      { id: 25, name: "广告管理", icon: "ep:picture", type: "menu" }
    ]
  },
  {
    id: 3,
    name: "运营管理",
    icon: "ep:data-analysis",
    type: "menu",
    children: [
      { id: 31, name: "订单管理", icon: "ep:shopping-cart", type: "menu" },
      { id: 32, name: "财务管理", icon: "ep:money", type: "menu" },
      { id: 33, name: "数据统计", icon: "ep:data-line", type: "menu" },
      { id: 34, name: "操作日志", icon: "ep:document-copy", type: "menu" }
    ]
  }
]);

// 角色用户数据
const roleUsers = ref([
  {
    id: 1,
    username: "admin",
    realName: "系统管理员",
    phone: "13800138000",
    email: "admin@example.com",
    status: "active"
  },
  {
    id: 2,
    username: "operator01",
    realName: "运营专员",
    phone: "13800138001",
    email: "operator@example.com",
    status: "active"
  }
]);

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  return dayjs(dateTime).format("YYYY-MM-DD HH:mm");
};

// 获取角色图标
const getRoleIcon = (code: string) => {
  const iconMap: Record<string, string> = {
    super_admin: "ep:crown",
    admin: "ep:user-filled",
    operator: "ep:service",
    user: "ep:user"
  };
  return iconMap[code] || "ep:avatar";
};

// 获取权限类型文本
const getPermissionTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    menu: "菜单",
    button: "按钮",
    api: "接口"
  };
  return typeMap[type] || "未知";
};

// 搜索
const handleSearch = () => {
  pagination.page = 1;
  loadRoleList();
};

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    name: "",
    code: "",
    status: "",
    dateRange: []
  });
  handleSearch();
};

// 新增角色
const handleCreate = () => {
  router.push("/role/create");
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRoles.value.length} 个角色吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API批量删除角色
    ElMessage.success("删除成功");
    selectedRoles.value = [];
    loadRoleList();
  } catch {
    // 用户取消
  }
};

// 导出数据
const handleExport = () => {
  // 这里应该调用导出API
  ElMessage.success("导出成功");
};

// 刷新
const handleRefresh = () => {
  loadRoleList();
};

// 选择变化
const handleSelectionChange = (selection: any[]) => {
  selectedRoles.value = selection;
};

// 状态变更
const handleStatusChange = async (role: any) => {
  const actionText = role.status === "enabled" ? "启用" : "禁用";

  try {
    // 这里应该调用API更新角色状态
    ElMessage.success(`${actionText}成功`);
  } catch (error) {
    // 恢复原状态
    role.status = role.status === "enabled" ? "disabled" : "enabled";
    ElMessage.error(`${actionText}失败`);
  }
};

// 查看角色
const handleView = (role: any) => {
  currentRole.value = role;
  detailVisible.value = true;
};

// 编辑角色
const handleEdit = (role: any) => {
  router.push(`/role/edit/${role.id}`);
};

// 权限配置
const handlePermission = (role: any) => {
  currentRole.value = role;
  // 设置已选中的权限
  checkedPermissions.value = role.permissions?.map((p: any) => p.id) || [];
  permissionVisible.value = true;
};

// 删除角色
const handleDelete = async (role: any) => {
  if (role.isSystem) {
    ElMessage.warning("系统角色不能删除");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除角色 "${role.name}" 吗？此操作不可恢复！`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API删除角色
    ElMessage.success("删除成功");
    loadRoleList();
  } catch {
    // 用户取消
  }
};

// 查看角色用户
const viewRoleUsers = (role: any) => {
  currentRole.value = role;
  usersVisible.value = true;
};

// 保存权限配置
const handleSavePermissions = () => {
  if (!permissionTreeRef.value) return;

  const checkedKeys = permissionTreeRef.value.getCheckedKeys();
  const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys();
  const allCheckedKeys = [...checkedKeys, ...halfCheckedKeys];

  // 这里应该调用API保存权限配置
  ElMessage.success("权限配置保存成功");
  permissionVisible.value = false;
};

// 分配用户
const handleAssignUsers = () => {
  ElMessage.info("分配用户功能开发中");
};

// 移除用户
const handleRemoveUser = async (user: any) => {
  try {
    await ElMessageBox.confirm(
      `确定要将用户 "${user.username}" 从当前角色中移除吗？`,
      "确认移除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    // 这里应该调用API移除用户
    ElMessage.success("移除成功");
  } catch {
    // 用户取消
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  loadRoleList();
};

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  loadRoleList();
};

// 加载角色列表
const loadRoleList = async () => {
  loading.value = true;
  try {
    // 这里应该调用API获取角色列表
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));
    pagination.total = 50; // 模拟总数
  } catch (error) {
    ElMessage.error("加载角色列表失败");
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  loadRoleList();
});
</script>

<style scoped lang="scss">
.role-list-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-card,
.action-card,
.table-card {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.search-form {
  .el-form-item {
    margin-bottom: 16px;
  }
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-left {
    display: flex;
    gap: 8px;
  }
}

.role-name {
  display: flex;
  align-items: center;
  gap: 8px;

  .role-icon {
    font-size: 16px;
    color: #409eff;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.role-detail {
  .role-permissions {
    margin-top: 20px;

    h4 {
      margin: 0 0 12px 0;
      font-size: 14px;
      font-weight: 600;
      color: #303133;
    }

    .permission-tree {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .permission-tag {
        margin-bottom: 4px;
      }
    }
  }
}

.permission-config {
  .config-header {
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f2f5;
    font-weight: 600;
    color: #303133;
  }

  .permission-tree {
    max-height: 400px;
    overflow-y: auto;

    .tree-node {
      display: flex;
      align-items: center;
      gap: 8px;
      flex: 1;

      .node-icon {
        font-size: 14px;
        color: #409eff;
      }

      .node-label {
        flex: 1;
      }

      .node-type {
        margin-left: auto;
      }
    }
  }
}

.role-users {
  .users-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 12px;
    border-bottom: 1px solid #f0f2f5;
    font-weight: 600;
    color: #303133;
  }
}

@media (max-width: 768px) {
  .role-list-container {
    padding: 10px;
  }

  .search-form {
    .el-form-item {
      width: 100%;
      margin-bottom: 12px;

      .el-input,
      .el-select,
      .el-date-picker {
        width: 100% !important;
      }
    }
  }

  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left {
      flex-wrap: wrap;
    }

    .action-right {
      align-self: flex-end;
    }
  }

  .users-header {
    flex-direction: column;
    gap: 12px;
    align-items: flex-start;
  }
}
</style>
